import { _decorator, Node, Touch, Component, Prefab, SpriteFrame, Event, Color, Graphics, director, Sprite, Texture2D, error, instantiate, warn, AudioClip, Label, Button, UIOpacity, UITransform, Vec3, ImageAsset, v3 } from 'cc';
import { Gomoku_Board, PieceType } from "./Gomoku_Board";
import { Gomoku_AI, AIDifficulty } from "./Gomoku_AI";
import { SSS_Consts } from "../../../Script/Data/SSS_Consts";
import Gomoku_WinPanel from "./UI/Gomoku_WinPanel";
import UI from "../../../Script/Manager/UI";
import Gomoku_LosePanel from "./UI/Gomoku_LosePanel";
import { bdlMgr } from "../../../Script/Manager/BundleManager_S";
import Gomoku_DifficultyPanel from "./UI/Gomoku_DifficultyPanel";
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';

const { ccclass, property } = _decorator;


// // === 1. 在这里添加悔棋记录类型 ===
interface MoveRecord {
        x: number;
        y: number;
        type: PieceType;
        pieceNode?: Node;
}

@ccclass('GomokuGameManager')
export default class Gomoku_GameManager extends Component {
        static Instance: Gomoku_GameManager;
        @property(Prefab)
        piecePrefab: Prefab | null = null;
        @property(Node)
        boardNode: Node | null = null;
        @property(SpriteFrame)
        blackPieceSprite: SpriteFrame | null = null;
        @property(SpriteFrame)
        whitePieceSprite: SpriteFrame | null = null;
        @property(Node)
        Button_back: Node | null = null;
        @property(Node)
        Button_refresh: Node | null = null;
        @property(Node)
        Button_undo: Node | null = null;
        @property(Node)
        Button_difficulty: Node | null = null;
        board: Gomoku_Board = new Gomoku_Board();
        ai: Gomoku_AI = new Gomoku_AI(AIDifficulty.Medium);
        isMyTurn: boolean = true;
        currentDifficulty: AIDifficulty = AIDifficulty.Medium;
        moveHistory: MoveRecord[] = [];
        canUndo: boolean = false;
        lastBlackMoveNode?: Node;
        lastWhiteMoveNode?: Node;
        gridSize: number = 50;
        onLoad() {
                Gomoku_GameManager.Instance = this;


                //        // // 添加组件检查
                //        // cc.log("=== 组件检查 ===");
                //        // cc.log(`boardNode: ${this.boardNode ? '已设置' : '未设置'}`);
                //        // cc.log(`piecePrefab: ${this.piecePrefab ? '已设置' : '未设置'}`);
                //        // cc.log(`blackPieceSprite: ${this.blackPieceSprite ? '已设置' : '未设置'}`);
                //        // cc.log(`whitePieceSprite: ${this.whitePieceSprite ? '已设置' : '未设置'}`);

                //        // if (this.boardNode) {
                //        //     cc.log(`boardNode位置: (${this.boardNode.x}, ${this.boardNode.y})`);
                //        //     cc.log(`boardNode大小: (${this.boardNode.width}, ${this.boardNode.height})`);
                //        // }

                this.drawBoard();
                this.createIntersectionPoints();

                // TODO
                // this.boardNode.on(Node.EventType.TOUCH_END, this.onTouch, this);

                this.AddListener();
                this.updateUndoButton();

                // 显示当前难度给玩家
                this.showCurrentDifficulty();
        }

        AddListener() {
                this.Button_back.on(Node.EventType.TOUCH_END, this.On_Button_back, this);
                this.Button_refresh.on(Node.EventType.TOUCH_END, this.On_Button_refresh, this);
                if (this.Button_undo) {
                        this.Button_undo.on(Node.EventType.TOUCH_END, this.On_Button_undo, this);
                }
                if (this.Button_difficulty) {
                        this.Button_difficulty.on(Node.EventType.TOUCH_END, this.On_Button_difficulty, this);
                }
        }

        On_Button_back() {
                director.loadScene(SSS_Consts.SceneName.MainScene);
                // cc.director.loadScene("MainScene");

                SSS_AudioManager.PlayButtonAudio();
        }
        On_Button_refresh() {
                Gomoku_GameManager.Instance.Replay();

                SSS_AudioManager.PlayButtonAudio();
        }
        Replay() {
                this.restartGame();

                // let currentSceneName = cc.director.getScene().name;
                // cc.director.loadScene(currentSceneName);
        }
        drawBoard() {
                // 创建棋盘背景和网格
                this.createBoardBackground();
                this.drawGridLines();
                this.drawStarPoints();
        }

        createBoardBackground() {
                // 创建棋盘背景节点
                const background = new Node('BoardBackground');
                background.parent = this.boardNode;
                background.setPosition(0, 0);

                // 设置背景大小
                const boardSize = 15;
                const totalSize = (boardSize - 1) * this.gridSize;
                const uiTransform = background.addComponent(UITransform);
                uiTransform.setContentSize(totalSize + this.gridSize, totalSize + this.gridSize);

                // 添加背景精灵组件
                const sprite = background.addComponent(Sprite);
                sprite.color = new Color(222, 184, 135); // 木色背景 #DEB887

                // 设置背景在最底层
                background.setSiblingIndex(0);
        }

        drawGridLines() {
                // 创建网格线节点
                const gridLines = new Node('GridLines');
                gridLines.parent = this.boardNode;
                gridLines.setPosition(0, 0);

                // 添加 Graphics 组件
                const graphics = gridLines.addComponent(Graphics);
                graphics.lineWidth = 2;
                graphics.strokeColor = Color.BLACK;

                const boardSize = 15;
                const totalSize = (boardSize - 1) * this.gridSize;
                const startPos = -totalSize / 2;

                // 绘制垂直线
                for (let i = 0; i < boardSize; i++) {
                        const x = startPos + i * this.gridSize;
                        graphics.moveTo(x, startPos);
                        graphics.lineTo(x, -startPos);
                }

                // 绘制水平线
                for (let i = 0; i < boardSize; i++) {
                        const y = startPos + i * this.gridSize;
                        graphics.moveTo(startPos, y);
                        graphics.lineTo(-startPos, y);
                }

                // 完成绘制
                graphics.stroke();

                // 设置网格线在背景之上
                gridLines.setSiblingIndex(1);
        }
        drawStarPoints() {
                // 创建星位点节点
                const starPoints = new Node('StarPoints');
                starPoints.parent = this.boardNode;
                starPoints.setPosition(0, 0);

                // 添加 Graphics 组件
                const graphics = starPoints.addComponent(Graphics);
                graphics.fillColor = Color.BLACK;

                const boardSize = 15;
                const totalSize = (boardSize - 1) * this.gridSize;
                const startPos = -totalSize / 2;

                // 星位坐标（天元和四个星位）
                const points = [
                        [7, 7],   // 天元
                        [3, 3],   // 左上星
                        [11, 3],  // 右上星
                        [3, 11],  // 左下星
                        [11, 11]  // 右下星
                ];

                // 绘制所有星位点
                points.forEach(([x, y]) => {
                        const posX = startPos + x * this.gridSize;
                        const posY = startPos + y * this.gridSize;
                        graphics.circle(posX, posY, 4);
                        graphics.fill();
                });

                // 设置星位点在网格线之上
                starPoints.setSiblingIndex(2);
        }
        createIntersectionPoints() {
                // 创建交叉点容器节点
                const intersectionsContainer = new Node('IntersectionPoints');
                intersectionsContainer.parent = this.boardNode;
                intersectionsContainer.setPosition(0, 0);

                const boardSize = 15;
                const totalSize = (boardSize - 1) * this.gridSize;
                const startPos = -totalSize / 2;

                // 为每个交叉点创建点击区域
                for (let x = 0; x < boardSize; x++) {
                        for (let y = 0; y < boardSize; y++) {
                                const intersection = new Node(`Intersection_${x}_${y}`);
                                intersection.parent = intersectionsContainer;

                                // 设置交叉点位置
                                const posX = startPos + x * this.gridSize;
                                const posY = startPos + y * this.gridSize;
                                intersection.setPosition(posX, posY);

                                // 设置点击区域大小
                                const transform = intersection.addComponent(UITransform);
                                transform.setContentSize(this.gridSize * 0.8, this.gridSize * 0.8);

                                // 添加按钮组件
                                const button = intersection.addComponent(Button);
                                button.transition = Button.Transition.NONE;

                                // 添加点击事件监听
                                intersection.on(Node.EventType.TOUCH_END, () => {
                                        this.onIntersectionClick(x, y);
                                }, this);

                                // 存储坐标信息
                                intersection['gridX'] = x;
                                intersection['gridY'] = y;
                        }
                }

                // 设置交叉点容器在星位点之上
                intersectionsContainer.setSiblingIndex(3);
        }
        //    // === 6. 记录每一步 ===
        recordMove(x: number, y: number, type: PieceType, pieceNode?: Node) {
                this.moveHistory.push({ x, y, type, pieceNode });
                this.updateUndoButton();
        }
        //    // === 7. 玩家和AI下棋时调用 recordMove ===
        onIntersectionClick(x: number, y: number) {
                console.log(`点击下棋=============`);
                console.log(`this.isMyTurn=============`, this.isMyTurn);

                if (!this.isMyTurn) return;

                console.log(`点击交汇点: (${x}, ${y})`);

                if (this.board.placePiece(x, y, PieceType.Black)) {
                        // cc.log("✅ 成功放置棋子");
                        const pieceNode = this.spawnPiece(x, y, PieceType.Black);
                        this.recordMove(x, y, PieceType.Black, pieceNode);
                        this.addLastMoveMark(pieceNode, PieceType.Black); // 添加最后落子标记
                        if (this.board.checkWin(x, y, PieceType.Black)) {
                                // cc.log("你赢了");
                                // this.showGameResult("你赢了！");

                                this.Win();

                                return;
                        }
                        this.isMyTurn = false;
                        this.scheduleOnce(() => this.aiTurn(), 0.5);
                } else {
                        // cc.log("❌ 无法放置棋子，位置已被占用");
                }
        }

        Win() {
                UI.Instance.CreatePanel_sub(`Gomoku_Prefab`, `UI/Gomoku_WinPanel`, Gomoku_WinPanel);
        }
        Lose() {
                UI.Instance.CreatePanel_sub(`Gomoku_Prefab`, `UI/Gomoku_LosePanel`, Gomoku_LosePanel);
        }

        onTouch(event: Touch) {
                if (!this.isMyTurn) return;

                // 获取触摸点的UI坐标
                const worldPos = event.getUILocation();

                // 转换为节点本地坐标
                const loc = this.boardNode.getComponent(UITransform)!.convertToNodeSpaceAR(v3(worldPos.x, worldPos.y));

                const boardSize = 15;
                const totalSize = (boardSize - 1) * this.gridSize;
                const startPos = -totalSize / 2;

                // 计算最近的网格交叉点
                const gridX = Math.round((loc.x - startPos) / this.gridSize);
                const gridY = Math.round((loc.y - startPos) / this.gridSize);

                // 检查是否在棋盘范围内
                if (gridX < 0 || gridX >= boardSize || gridY < 0 || gridY >= boardSize) {
                        return;
                }

                // 尝试在计算出的位置放置棋子
                this.onIntersectionClick(gridX, gridY);
        }
        aiTurn() {
                const [x, y] = this.ai.getMove(this.board, PieceType.White);
                if (this.board.placePiece(x, y, PieceType.White)) {
                        const pieceNode = this.spawnPiece(x, y, PieceType.White);
                        this.recordMove(x, y, PieceType.White, pieceNode);
                        this.addLastMoveMark(pieceNode, PieceType.White); // 添加最后落子标记
                        if (this.board.checkWin(x, y, PieceType.White)) {
                                // cc.log("AI 赢了");
                                // this.showGameResult("AI 赢了！");

                                this.Lose();

                                return;
                        }
                }
                this.isMyTurn = true;
        }
        //    // === 8. spawnPiece 返回 cc.Node ===
        spawnPiece(x: number, y: number, type: PieceType): Node {
                console.log("=== 生成棋子 ===");

                if (!this.piecePrefab) {
                        error("❌ 棋子预制体未设置！");
                        return null;
                }

                const piece = instantiate(this.piecePrefab);
                piece.parent = this.boardNode;

                const boardSize = 15;
                const totalSize = (boardSize - 1) * this.gridSize;
                const startPos = -totalSize / 2;
                const pieceX = startPos + x * this.gridSize;
                const pieceY = startPos + y * this.gridSize;

                piece.setPosition(pieceX, pieceY);
                piece.zIndex = 10; // 确保棋子在网格线之上

                // cc.log(`棋子位置: (${pieceX}, ${pieceY})`);
                // cc.log(`棋子层级: ${piece.zIndex}`);

                const sprite = piece.getComponent(Sprite);
                if (sprite) {
                        // 尝试使用图片设置
                        let imageSet = false;

                        if (type === PieceType.Black) {
                                if (this.blackPieceSprite) {
                                        sprite.spriteFrame = this.blackPieceSprite;
                                        // cc.log("✅ 设置黑棋图片");
                                        // cc.log(`黑棋图片名称: ${this.blackPieceSprite.name}`);
                                        imageSet = true;

                                        let name = `tile click`;

                                        let audio_root = `audio/${name}`;
                                        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, audio_root, AudioClip).then(res => {
                                                SSS_AudioManager.Instance.playSFX(res, false);
                                        });
                                } else {
                                        warn("⚠️ 黑棋图片未设置，使用颜色区分");
                                }
                        } else if (type === PieceType.White) {
                                if (this.whitePieceSprite) {
                                        sprite.spriteFrame = this.whitePieceSprite;
                                        // cc.log("✅ 设置白棋图片");
                                        // cc.log(`白棋图片名称: ${this.whitePieceSprite.name}`);
                                        imageSet = true;

                                        let name = `tile click blocked`;
                                        let audio_root = `audio/${name}`;
                                        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, audio_root, AudioClip).then(res => {
                                                SSS_AudioManager.Instance.playSFX(res, false);
                                        });
                                } else {
                                        warn("⚠️ 白棋图片未设置，使用颜色区分");
                                }
                        }

                        // sprite.spriteFrame = this.whitePieceSprite;


                        // // 如果图片设置失败，使用颜色区分作为备选方案
                        // if (!imageSet) {
                        //     if (type === PieceType.Black) {
                        //         piece.color = cc.Color.BLACK;
                        //         cc.log("✅ 设置黑色棋子");
                        //     } else if (type === PieceType.White) {
                        //         piece.color = cc.Color.WHITE;
                        //         // 为白色棋子添加边框
                        //         const border = new cc.Node();
                        //         border.parent = piece;
                        //         border.setPosition(0, 0);
                        //         border.zIndex = 1;

                        //         const borderGraphics = border.addComponent(cc.Graphics);
                        //         borderGraphics.strokeColor = cc.Color.BLACK;
                        //         borderGraphics.lineWidth = 2;
                        //         borderGraphics.circle(0, 0, 18);
                        //         borderGraphics.stroke();

                        //         cc.log("✅ 设置白色棋子（带边框）");
                        //     }
                        // }
                } else {
                        console.error("❌ 棋子预制体缺少Sprite组件！");
                        return null;
                }

                // 添加棋子阴影效果
                // this.addPieceShadow(piece);

                console.log(`✅ 棋子生成完成: 位置(${x}, ${y}), 类型: ${type === PieceType.Black ? '黑' : '白'}`);
                return piece;
        }
        addPieceShadow(piece: Node) {
                // 创建阴影效果
                const shadow = new Node();
                shadow.parent = piece;
                shadow.setPosition(2, -2);
                // shadow.zIndex = 2; // 阴影在棋子下方

                const shadowSprite = shadow.addComponent(Sprite);
                const pieceSprite = piece.getComponent(Sprite);
                if (pieceSprite && pieceSprite.spriteFrame) {
                        shadowSprite.spriteFrame = pieceSprite.spriteFrame;
                        // shadow.color = new Color(0, 0, 0, 100);
                        shadowSprite.color = new Color(0, 0, 0, 100);
                        shadow.scale = new Vec3(0.95, 0.95, 1);
                }
        }
        showGameResult(message: string) {
                // 创建结果显示
                const resultNode = new Node();
                resultNode.parent = this.node;
                resultNode.setPosition(0, 0);
                // resultNode.zIndex = 10; // 确保结果显示在最上层

                const label = resultNode.addComponent(Label);
                label.string = message;
                label.fontSize = 48;
                label.color = Color.RED;

                // 添加重新开始按钮
                this.addRestartButton();
        }
        addRestartButton() {
                const button = new Node();
                button.parent = this.node;
                button.setPosition(0, -100);
                // button.zIndex = 10; // 确保按钮在最上层

                const buttonSprite = button.addComponent(Sprite);
                const label = button.addComponent(Label);
                label.string = "重新开始";
                label.fontSize = 24;
                label.color = Color.WHITE;

                const buttonComp = button.addComponent(Button);
                button.on('click', () => {
                        this.restartGame();
                });
        }
        //    // === 4. 新增悔棋功能 ===
        undoLastMove() {
                if (this.moveHistory.length === 0) return;

                // 先清除所有高亮标记
                this.removeLastMoveMark();

                // 悔棋两次（玩家一步+AI一步）
                for (let i = 0; i < 2 && this.moveHistory.length > 0; i++) {
                        const lastMove = this.moveHistory.pop();
                        if (lastMove) {
                                this.board.grid[lastMove.x][lastMove.y] = PieceType.None;
                                if (lastMove.pieceNode && lastMove.pieceNode.isValid) {
                                        lastMove.pieceNode.destroy();
                                }
                        }
                }
                this.isMyTurn = true;
                this.updateUndoButton();

                // 悔棋后，为最后一个棋子添加高亮标记
                if (this.moveHistory.length > 0) {
                        const lastMove = this.moveHistory[this.moveHistory.length - 1];
                        if (lastMove.pieceNode && lastMove.pieceNode.isValid) {
                                this.addLastMoveMark(lastMove.pieceNode, lastMove.type);
                        }
                }
                // cc.log("悔棋完成");
        }
        //    // === 5. 更新悔棋按钮状态 ===
        updateUndoButton() {
                this.canUndo = this.moveHistory.length >= 2;
                if (this.Button_undo) {
                        this.Button_undo.getComponent(Button).interactable = this.canUndo;
                        this.Button_undo.getComponent(UIOpacity).opacity = this.canUndo ? 255 : 128;
                }
        }
        //    // === 3. 新增悔棋按钮事件 ===
        On_Button_undo() {
                if (this.canUndo) {
                        this.undoLastMove();
                        SSS_AudioManager.PlayButtonAudio();
                }
        }
        //    // === 新增：难度选择按钮事件 ===
        On_Button_difficulty() {
                this.openDifficultyPanel();
                SSS_AudioManager.PlayButtonAudio();
        }
        //    // === 新增：移除上一个最后落子标记 ===
        removeLastMoveMark() {
                if (this.lastBlackMoveNode && this.lastBlackMoveNode.isValid) {
                        const highlight = this.lastBlackMoveNode.getChildByName("black_highlight");
                        if (highlight && highlight.isValid) {
                                highlight.destroy();
                        }
                        this.lastBlackMoveNode = null;
                }
                if (this.lastWhiteMoveNode && this.lastWhiteMoveNode.isValid) {
                        const highlight = this.lastWhiteMoveNode.getChildByName("white_highlight");
                        if (highlight && highlight.isValid) {
                                highlight.destroy();
                        }
                        this.lastWhiteMoveNode = null;
                }
        }
        //    // === 新增：添加新的最后落子标记 ===
        addLastMoveMark(pieceNode: Node, pieceType: PieceType) {
                // 根据棋子类型添加不同颜色的标记
                if (pieceType === PieceType.Black) {
                        this.addBlackMoveMark(pieceNode);
                } else if (pieceType === PieceType.White) {
                        this.addWhiteMoveMark(pieceNode);
                }
        }
        //    // === 新增：添加黑方最后落子标记 ===
        addBlackMoveMark(pieceNode: Node) {
                // 检查棋子节点是否有效
                if (!pieceNode || !pieceNode.isValid) {
                        return;
                }

                // 移除之前的黑方标记
                if (this.lastBlackMoveNode && this.lastBlackMoveNode.isValid) {
                        const highlight = this.lastBlackMoveNode.getChildByName("black_highlight");
                        if (highlight && highlight.isValid) {
                                highlight.destroy();
                        }
                }

                // 创建黑方高亮边框
                const highlight = new Node();
                highlight.name = "black_highlight";
                highlight.parent = pieceNode;
                highlight.setPosition(0, 0);
                highlight.zIndex = 1; // 确保在棋子之上

                // 添加高亮图形组件
                const graphics = highlight.addComponent(Graphics);
                graphics.lineWidth = 5;
                graphics.strokeColor = this.黑子边框颜色; // 红色高亮边框（黑方）

                this.drawSquareBorder(graphics);

                this.lastBlackMoveNode = pieceNode;
        }
        黑子边框颜色 = new Color().fromHEX(`#C6CB7B`);
        白子边框颜色 = new Color().fromHEX(`#FF8652`);
        //    // === 新增：添加白方最后落子标记 ===
        addWhiteMoveMark(pieceNode: Node) {
                // 检查棋子节点是否有效
                if (!pieceNode || !pieceNode.isValid) {
                        return;
                }

                // 移除之前的白方标记
                if (this.lastWhiteMoveNode && this.lastWhiteMoveNode.isValid) {
                        const highlight = this.lastWhiteMoveNode.getChildByName("white_highlight");
                        if (highlight && highlight.isValid) {
                                highlight.destroy();
                        }
                }

                // 创建白方高亮边框
                const highlight = new Node();
                highlight.name = "white_highlight";
                highlight.parent = pieceNode;
                highlight.setPosition(0, 0);
                highlight.zIndex = 1; // 确保在棋子之上

                // 添加高亮图形组件
                const graphics = highlight.addComponent(Graphics);
                graphics.lineWidth = 5;
                graphics.strokeColor = this.白子边框颜色; // 蓝色高亮边框（白方）

                this.drawSquareBorder(graphics);

                this.lastWhiteMoveNode = pieceNode;
        }
        //    // === 新增：绘制正方形边框的通用方法 ===
        drawSquareBorder(graphics: Graphics) {
                // 正方形虚线边框参数
                const size = 32; // 正方形边长
                const cornerLength = 4; // 四个角的实线长度（更短）
                const gapLength = 8; // 中间空白的长度

                // 绘制四个角的实线
                // 左下角
                graphics.moveTo(-size / 2, -size / 2);
                graphics.lineTo(-size / 2 + cornerLength, -size / 2);
                graphics.moveTo(-size / 2, -size / 2);
                graphics.lineTo(-size / 2, -size / 2 + cornerLength);

                // 右下角
                graphics.moveTo(size / 2, -size / 2);
                graphics.lineTo(size / 2 - cornerLength, -size / 2);
                graphics.moveTo(size / 2, -size / 2);
                graphics.lineTo(size / 2, -size / 2 + cornerLength);

                // 左上角
                graphics.moveTo(-size / 2, size / 2);
                graphics.lineTo(-size / 2 + cornerLength, size / 2);
                graphics.moveTo(-size / 2, size / 2);
                graphics.lineTo(-size / 2, size / 2 - cornerLength);

                // 右上角
                graphics.moveTo(size / 2, size / 2);
                graphics.lineTo(size / 2 - cornerLength, size / 2);
                graphics.moveTo(size / 2, size / 2);
                graphics.lineTo(size / 2, size / 2 - cornerLength);

                // 绘制四边的实线（中间留空）
                // 上边实线（分两段）
                graphics.moveTo(-size / 2 + cornerLength, size / 2);
                graphics.lineTo(-size / 2 + (size - cornerLength * 2 - gapLength) / 2, size / 2);
                graphics.moveTo(size / 2 - (size - cornerLength * 2 - gapLength) / 2, size / 2);
                graphics.lineTo(size / 2 - cornerLength, size / 2);

                // 下边实线（分两段）
                graphics.moveTo(-size / 2 + cornerLength, -size / 2);
                graphics.lineTo(-size / 2 + (size - cornerLength * 2 - gapLength) / 2, -size / 2);
                graphics.moveTo(size / 2 - (size - cornerLength * 2 - gapLength) / 2, -size / 2);
                graphics.lineTo(size / 2 - cornerLength, -size / 2);

                // 左边实线（分两段）
                graphics.moveTo(-size / 2, -size / 2 + cornerLength);
                graphics.lineTo(-size / 2, -size / 2 + (size - cornerLength * 2 - gapLength) / 2);
                graphics.moveTo(-size / 2, size / 2 - (size - cornerLength * 2 - gapLength) / 2);
                graphics.lineTo(-size / 2, size / 2 - cornerLength);

                // 右边实线（分两段）
                graphics.moveTo(size / 2, -size / 2 + cornerLength);
                graphics.lineTo(size / 2, -size / 2 + (size - cornerLength * 2 - gapLength) / 2);
                graphics.moveTo(size / 2, size / 2 - (size - cornerLength * 2 - gapLength) / 2);
                graphics.lineTo(size / 2, size / 2 - cornerLength);

                graphics.stroke();
        }
        restartGame() {
                console.log("从新开始");

                // director.loadScene("Gomoku_Game");
                let currentSceneName = director.getScene().name;
                director.loadScene(currentSceneName);

                // // 清除所有棋子
                // this.boardNode.removeAllChildren();

                // // 重新绘制棋盘
                // this.drawBoard();

                // // 重置游戏状态
                // this.board.reset();
                // this.isMyTurn = true;
                // this.moveHistory = [];
                // this.updateUndoButton();

                // // 清除最后落子标记
                // this.removeLastMoveMark();
        }
        //    // === 新增：切换AI难度 ===
        setDifficulty(difficulty: AIDifficulty) {
                this.currentDifficulty = difficulty;
                this.ai = new Gomoku_AI(difficulty);
                console.log(`AI难度已切换为: ${this.getDifficultyName(difficulty)}`);
        }
        //    // === 新增：获取难度名称 ===
        getDifficultyName(difficulty: AIDifficulty): string {
                switch (difficulty) {
                        case AIDifficulty.Easy: return "简单";
                        case AIDifficulty.Medium: return "中等";
                        case AIDifficulty.Hard: return "困难";
                        default: return "未知";
                }
        }
        //    // === 新增：获取当前难度名称 ===
        getCurrentDifficultyName(): string {
                return this.getDifficultyName(this.currentDifficulty);
        }
        //    // === 新增：显示当前难度给玩家 ===
        showCurrentDifficulty() {
                const difficultyName = this.getCurrentDifficultyName();
                console.log(`当前AI难度: ${difficultyName}`);

                // 在控制台显示当前难度
                console.log(`五子棋游戏已启动，当前AI难度设置为: ${difficultyName}`);

                Gomoku_DifficultyPanel.Instance.updateButtonHighlights();

        }
        //    // === 新增：打开难度选择面板 ===
        openDifficultyPanel() {
                UI.Instance.CreatePanel_sub(`Gomoku_Prefab`, `UI/Gomoku_DifficultyPanel`, Gomoku_DifficultyPanel);
        }
}